<template>
  <div class="app-container customer-div">
      <div>
        <el-menu :default-active="params.tab" class="el-menu-demo" mode="horizontal" @select="changeTab">
          <el-menu-item index="all">总览</el-menu-item>
          <el-menu-item :index="item" v-for="(item,index) in categoryNames" :key="index">{{item}}</el-menu-item>
        </el-menu>
        <div id="chart-div">
          <div class="tiaojian-div" style="padding-top:20px">
            <el-form :inline="true" :model="params" size="mini" label-width="90px" v-if="params.tab == 'all'">
              <el-form-item label="日期：">
                <el-date-picker
                        :default-time="['00:00:00', '23:59:59']"
                        v-model="params.date"
                        type="date"
                        format="yyyy 年 MM 月 dd 日"
                        value-format="yyyy-MM-dd">
                </el-date-picker>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleSearchList">查询</el-button>
              </el-form-item>
            </el-form>
            <el-form :inline="true" :model="params" size="mini" label-width="90px" v-if="params.tab != 'all'">
              <el-form-item label="日期：">
                <el-date-picker
                        :default-time="['00:00:00', '23:59:59']"
                        v-model="params.date"
                        type="daterange"
                        format="yyyy 年 MM 月 dd 日"
                        value-format="yyyy-MM-dd"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="牌号：">
                <el-select v-model="params.goodsKingId" class="input-width" style="width:195px" placeholder="请选择" clearable filterable>
                  <el-option :value="item.kingId" :label="item.goodsSn" :key="item.kingId" v-for="item in options"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                  <el-button type="primary" @click="handleSearchList">查询</el-button>
              </el-form-item>
            </el-form>
          </div>
          <div class="number-div" v-if="params.tab == 'all'">
              <div class="number-col" v-for="(item,index) in categoryNames">
                  <div class="number-type" :style="{color:priceTypeList[index] == '涨' ? 'red' : priceTypeList[index] == '跌' ? 'green' : ''}">{{priceTypeList[index]}}</div>
                  <div class="number-name">{{item}}</div>
              </div>

          </div>
          <div class="number-div" v-if="params.tab != 'all'">
            <div class="number-col">
              <div class="number-type">{{purchaseNumSum}}</div>
              <div class="number-name">采购总量</div>
            </div>
            <div class="number-col">
              <div class="number-type">{{saleNumSum}}</div>
              <div class="number-name">销售总量</div>
            </div>
            <div class="number-col">
              <div class="number-type">{{shipNumSum}}</div>
              <div class="number-name">发货总量</div>
            </div>
          </div>
          <div id="myChart" :style="{'height':'550px'}" v-loading="loadingChart"></div>
        </div>
      </div>

      <!--数据列表-->
      <div v-if="params.tab == 'all'">
        <div class="tiaojian-div" style="margin-top:50px;clear: both;border-top:1px solid #eee;padding-top:40px;margin-bottom: 20px" >
          <el-button
                  size="small"
                  @click="showNewDialog"
                  type="primary">
            新增报价
          </el-button>
        </div>
        <div class="table-container" style="margin-top:0">
          <el-table
                  v-loading="loading"
                  :data="list"
                  border
                  style="width: 100%;margin-top:0">
            <el-table-column
                    prop="categoryName"
                    label="品名"
                    align="center">
            </el-table-column>
            <el-table-column
                    prop="addDate"
                    label="日期"
                    align="center">
            </el-table-column>
            <el-table-column
                    align="center"
                    prop="priceType"
                    label="涨跌">
            </el-table-column>
            <el-table-column
                    align="center"
                    prop="categorySaleNum"
                    label="销售量">
            </el-table-column>
            <el-table-column
                    align="center"
                    prop="categoryPurchaseNum"
                    label="采购量">
            </el-table-column>
            <el-table-column
                    prop="categoryShipNum"
                    label="发货量"
                    align="center">
            </el-table-column>
            <el-table-column
                    prop="goodsSn"
                    label="牌号"
                    align="center">
            </el-table-column>
            <el-table-column
                    prop="goodsPrice"
                    label="价格"
                    align="center">
            </el-table-column>
          </el-table>
        </div>
        <div class="pagination-container">
          <el-pagination
                  background
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                  layout="total, sizes,prev, pager, next,jumper"
                  :current-page.sync="params.pageNum"
                  :page-size="params.pageSize"
                  :page-sizes="[10,15,20]"
                  :total="count">
          </el-pagination>
        </div>
      </div>

      <!--数据列表-->
      <div v-if="params.tab != 'all'">
        <div class="tiaojian-div" style="margin-top:50px;clear: both;border-top:1px solid #eee;padding-top:40px;margin-bottom:20px;" >
          <el-button-group>
            <el-button :type="sort == 1 ||  sort == 2  ? 'primary' : '' " style="width:100px;height:40px" @click="changeSort('sale')">
              <span style="float:left;">销售量</span>
              <i class="el-icon-caret-bottom" style="float:left;margin-top: 4px;margin-left:2px" :style="{color:sort == 1 ? '#fff' : '#ccc'}"></i>
              <i class="el-icon-caret-top" style="float:left;margin-top: -4px;margin-left:-14px" :style="{color:sort == 2 ? '#fff' : '#ccc'}"></i>
            </el-button>
            <el-button  :type="sort == 3 ||  sort == 4 ? 'primary' : '' " style="width:100px;height:40px" @click="changeSort('purch')">
              <span style="float:left;">采购量</span>
              <i class="el-icon-caret-bottom" style="float:left;margin-top: 4px;margin-left:2px" :style="{color:sort == 3 ? '#fff' : '#ccc'}"></i>
              <i class="el-icon-caret-top" style="float:left;margin-top: -4px;margin-left:-14px" :style="{color:sort == 4 ? '#fff' : '#ccc'}"></i>
            </el-button>
            <el-button  :type="sort == 5 ||  sort == 6 ? 'primary' : '' " style="width:100px;height:40px" @click="changeSort('send')">
              <span style="float:left;">发货量</span>
              <i class="el-icon-caret-bottom" style="float:left;margin-top: 4px;margin-left:2px" :style="{color:sort == 5 ? '#fff' : '#ccc'}"></i>
              <i class="el-icon-caret-top" style="float:left;margin-top: -4px;margin-left:-14px" :style="{color:sort == 6 ? '#fff' : '#ccc'}"></i>
            </el-button>
          </el-button-group>
        </div>
        <div class="table-container" style="margin-top:0">
          <el-table
                  v-loading="loading"
                  :data="list"
                  border
                  style="width: 100%;margin-top:0">
            <el-table-column
                    prop="categoryName"
                    label="品名"
                    align="center">
            </el-table-column>
            <el-table-column
                    prop="goodsSn"
                    label="牌号"
                    align="center">
            </el-table-column>
            <el-table-column
                    align="center"
                    prop="addDate"
                    label="日期">
            </el-table-column>
            <el-table-column
                    align="center"
                    label="牌号销售量">
              <template slot-scope="scope">
                <el-link type="primary" @click="showData(1,scope.row)">{{scope.row.goodsSaleNum}}</el-link>
              </template>
            </el-table-column>
            <el-table-column
                    align="center"
                    label="牌号采购量">
              <template slot-scope="scope">
                <el-link type="primary" @click="showData(2,scope.row)">{{scope.row.goodsPurchaseNum}}</el-link>
              </template>
            </el-table-column>
            <el-table-column
                    label="牌号发货量"
                    align="center">
              <template slot-scope="scope">
                <el-link type="primary" @click="showData(3,scope.row)">{{scope.row.goodsShipNum}}</el-link>
              </template>
            </el-table-column>
            <el-table-column
                    prop="priceType"
                    label="涨跌"
                    align="center">
            </el-table-column>
          </el-table>
        </div>
        <div class="pagination-container">
          <el-pagination
                  background
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                  layout="total, sizes,prev, pager, next,jumper"
                  :current-page.sync="params.pageNum"
                  :page-size="params.pageSize"
                  :page-sizes="[10,15,20]"
                  :total="count">
          </el-pagination>
        </div>
      </div>

    <!--新增报价-->
    <el-dialog
            :close-on-click-modal="false"
            title="新增报价"
            :beforeClose="handleClose"
            :visible.sync="dialogVisible"
            width="400px">
        <el-form :model="form" size="mini" label-width="100px" :rules="rules" ref="form">
          <el-form-item label="牌号：" prop="goodsKingId">
            <el-select v-model="form.goodsKingId" class="input-width" style="width:195px" placeholder="请选择" clearable filterable>
              <el-option :value="item.kingId" :label="item.goodsSn" :key="item.kingId" v-for="item in options"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="价格：" prop="goodsPrice">
            <el-input v-model="form.goodsPrice" style="width:195px"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="handleClose">取 消</el-button>
            <el-button type="primary" @click="handleConfirm" :loading="btnLoading">确 定</el-button>
        </span>
    </el-dialog>

    <!--数据表格-->
    <el-dialog
            :close-on-click-modal="false"
            title="数据来源"
            :visible.sync="dialogVisible2"
            width="800px">
       <el-table border :data="popList"  v-loading="popLoading" v-if="dataType == 1">
        <el-table-column label="销售合同"  align="center" width="180">
          <template slot-scope="scope"><el-link @click="toOrderDetail(scope.row)"  type="primary">{{scope.row.orderSn}}</el-link></template>
        </el-table-column>
        <el-table-column label="客户名称"  header-align="center" width="180">
          <template slot-scope="scope">{{scope.row.customerName}}</template>
        </el-table-column>
        <el-table-column label="数量" align="center">
          <template slot-scope="scope">{{scope.row.goodsNum}}</template>
        </el-table-column>
        <el-table-column label="业务员" align="center">
          <template slot-scope="scope">{{scope.row.createUserName}}</template>
        </el-table-column>
        <el-table-column label="状态" align="center">
          <template slot-scope="scope">
              {{scope.row.orderState}}
          </template>
        </el-table-column>
      </el-table>
      <el-table border :data="popList"  v-loading="popLoading" v-if="dataType == 2">
        <el-table-column label="采购合同"  align="center" width="180">
          <template slot-scope="scope"><el-link @click="toInfo(scope.row)" type="primary">{{scope.row.orderSn}}</el-link></template>
        </el-table-column>
        <el-table-column label="供应商"  header-align="center" width="180">
          <template slot-scope="scope">{{scope.row.supplierName}}</template>
          <template slot-scope="scope">{{scope.row.supplierName}}</template>
        </el-table-column>
        <el-table-column label="数量" align="center">
          <template slot-scope="scope">{{scope.row.goodsNum}}</template>
        </el-table-column>
        <el-table-column label="采购员" align="center">
          <template slot-scope="scope">{{scope.row.createUserName}}</template>
        </el-table-column>
        <el-table-column label="状态" align="center">
          <template slot-scope="scope">
            {{scope.row.orderState}}
          </template>
        </el-table-column>
      </el-table>
      <el-table border :data="popList"  v-loading="popLoading" v-if="dataType == 3">
        <el-table-column label="发货单号"  align="center" width="180">
          <template slot-scope="scope"><el-link @click="toDeliverCon(scope.row)"  type="primary">{{scope.row.deliverSn}}</el-link></template>
        </el-table-column>
        <el-table-column label="客户"  header-align="center" width="180">
          <template slot-scope="scope">{{scope.row.customerName}}</template>
        </el-table-column>
        <el-table-column label="发货数量" align="center">
          <template slot-scope="scope">{{scope.row.shipNum}}</template>
        </el-table-column>
        <el-table-column label="状态" align="center">
          <template slot-scope="scope">
            {{scope.row.deliverState}}
          </template>
        </el-table-column>
      </el-table>
      <div style="overflow: hidden">
          <div class="pagination-container">
            <el-pagination
                    background
                    @size-change="handleSizeChange2"
                    @current-change="handleCurrentChange2"
                    layout="total, sizes,prev, pager, next,jumper"
                    :current-page.sync="popParams.pageNum"
                    :page-size="popParams.pageSize"
                    :page-sizes="[10,15,20]"
                    :total="popCount">
            </el-pagination>
          </div>
     </div>

    </el-dialog>
  </div>
</template>

<script>
  import { myGoodsClass,goodsReport,getSaleDetailList,dayCategoryPrice,dayGoodsPrice,addGoodsPrice,goodsPricePriceList,categoryPriceSummary,goodsPriceSaleOrderList,goodsPricePurchaseOrderList,goodsPriceDeliverList} from '@/api/partner'
  import {goodsList} from '@/api/company'
  import {formatDate} from '@/utils/date';
  import store from '@/store'
  import { mapGetters } from 'vuex'
  import {validateCommission} from '@/utils/validate';

  export default {
    name: "goodsAnalysis",
    data(){
      const isvalidateCommission = (rule, value, callback) => {
        if (!validateCommission(parseFloat(value))) {
          callback(new Error('非负整数或小数'))
        } else if(value > 99999999){
          callback(new Error('最大值为99999999'))
        }else {
          callback()
        }
      };
      return{
        roles:store.getters.roles ? store.getters.roles : [],
        params:{
          goodsKingId:'',
          tab:'all',
          date:'',
          pageNum:1,
          pageSize:10,
        },
        loadingChart:false,
        options:[],
        curtGoodsSn:'',
        sort:0,
        list:[],
        count:0,
        loading:false,

        form:{
          goodsKingId:'',
          goodsPrice:''
        },
        btnLoading:false,
        dialogVisible:false,
        rules:{
          goodsKingId :[{required: true, trigger: 'change' ,message: '请选择商品牌号',}],
          goodsPrice :[{required: true, trigger: 'blur' ,validator: isvalidateCommission}],
        },
        dialogVisible2:false,
        dataType:'',
        categoryNames:[],
        priceTypeList:[],
        purchaseNumSum :'',
        saleNumSum :'',
        shipNumSum:'',
        cutGoodsKingId:'',
        popParams:{
          pageNum:1,
          pageSize:10,
        },
        popList:[],
        popCount:0,
        popLoading:false,
        cutAddDate:'',
      }
    },
    computed: {
      ...mapGetters([
        'name',
        'mobile',
        'userId'
      ]),
    },
    created() {
        this.changeTab('all');
    },
    filters: {

    },
    methods:{

      //查看发货单
      toDeliverCon(item){
        let routeData = this.$router.resolve({name:'deliverCon',query:{id:item.deliverId,type:'see'}});
        window.open(routeData.href);
      },
      //订单详情
      toOrderDetail(item){
        let routeData = this.$router.resolve({name:'purchaseDetail',query:{id:item.orderId,type:'see'}});
        window.open(routeData.href);
      },

      //去采购合同详情页
      toInfo(item){
        let routeData = this.$router.resolve({name:'purchaseContractDetail',query:{id:item.orderId}});
        window.open(routeData.href);
      },

      //显示数据来源
      showData(dataType,item){
        this.dataType = dataType;
        this.cutGoodsKingId = item.goodsKingId;
        this.cutAddDate = item.addDate
        this.popParams.pageNum = 1;
        this.dialogVisible2 = true;
        this.getGoodsDateList();
      },
      handleSizeChange2(val){
        this.popParams.pageNum = 1;
        this.popParams.pageSize = val;
        this.getGoodsDateList();
      },

      handleCurrentChange2(val){
        this.popParams.pageNum = val;
        this.getGoodsDateList();
      },

      //指定商品某时间段销售，采购，发货记录
      getGoodsDateList(){
        let fn;
        if(this.dataType == 1){
          fn = goodsPriceSaleOrderList
        }else if(this.dataType == 2){
          fn = goodsPricePurchaseOrderList
        }else if(this.dataType == 3){
          fn = goodsPriceDeliverList
        }
        this.popLoading = true;
        fn({goodsKingId:this.cutGoodsKingId,addDate:this.cutAddDate,pageNum:this.popParams.pageNum,pageSize:this.popParams.pageSize}).then((res)=>{
                this.popList = res.list;
                this.popCount = res.count;
                this.popLoading = false;
        }).catch(()=>{
                this.popLoading = false;
        })
      },
      //显示新增报价
      showNewDialog(){
          this.dialogVisible = true;
          this.form.goodsKingId = '';
          this.form.goodsPrice = '';
      },
      //提交新增
      handleConfirm(){
        this.$refs['form'].validate((valid) => {
          if (valid) {
            this.btnLoading = true;
            addGoodsPrice({goodsKingId:this.form.goodsKingId,goodsPrice:this.form.goodsPrice}).then(()=>{
              this.btnLoading = false;
              this.dialogVisible = false;
              this.handleSearchList()
            }).catch(()=>{
              this.btnLoading = false;
            })
          }
        })
      },

      handleClose(){
        this.dialogVisible = false;
      },

      //切换排序
      changeSort(type){
        switch (type) {
          case 'sale':
            this.sort = this.sort == 1 ? 2 : 1;
            break;
          case 'purch':
            this.sort = this.sort == 3 ? 4 : 3;
            break;
          case 'send':
            this.sort = this.sort == 5 ? 6 : 5;
            break;
        }
        this.handleSearchList()
      },

      //获取商品列表
      getGoodsList(){
        if(this.params.tab != 'all'){
          goodsList({goodsName:this.params.tab}).then((res)=>{
            this.options = res.list;
          })
        }else{
          goodsList().then((res)=>{
            this.options = res.list;
          })
        }

      },
      //切换分类
      changeTab(key){
        this.params.tab = key;
        let time = new Date();
        let day = time - time % (24 * 60 * 60 * 1000) - 8 * 60 * 60 * 1000;
        let end = new Date(day + 24 * 60 * 60 * 1000-1000);
        let start;
        if(key == 'all'){
          this.params.date = formatDate(end, 'yyyy-MM-dd');
          console.log(formatDate(end, 'yyyy-MM-dd'))
        }else{
          this.params.goodsKingId = '';
          this.params.date = [];
          start = new Date(day - 7*24 * 60 * 60 * 1000);
          let endDate = formatDate(end, 'yyyy-MM-dd');
          let startDate = formatDate(start, 'yyyy-MM-dd');
          this.params.date = [startDate,endDate];
        }
        this.getGoodsList();
        this.handleSearchList();
      },

      //获取品类列表及图表数据
      getCategoryList(){
        if(this.params.tab=='all'){
          dayCategoryPrice({addDate:this.params.date}).then(response => {
            this.categoryNames = response.categoryNames;
            this.drawCaiGouCount(response.categoryNames,response.categorySaleNumList,response.categoryPurchaseNumList,response.categoryShipNumList);
            this.priceTypeList = response.priceTypeList;
          }).catch(()=>{

          });
        }else{
          categoryPriceSummary({addDate:this.params.date,goodsKingId:this.params.goodsKingId,categoryName:this.params.tab}).then(response => {
            this.drawCaiGouCount(response.dateList,response.saleNumList,response.purchaseNumList,response.shipNumList);
            this.purchaseNumSum = response.purchaseNumSum;
            this.saleNumSum = response.saleNumSum;
            this.shipNumSum = response.shipNumSum;
          }).catch(()=>{

          });
        }

      },

      //画图表
      drawCaiGouCount(x,y1,y2,y3){
        let myChart = this.$echarts.init(document.getElementById('myChart'));


        // 绘制图表
        myChart.setOption({
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          legend: {
            data: ['销售量', '采购量', '发货量']
          },

          xAxis: [
            {
              type: 'category',
              axisTick: {show: false},
              data: x
            }
          ],
          yAxis: [
            {
              type: 'value'
            }
          ],
          series: [
            {
              name: '销售量',
              type: 'bar',
              barGap: 0,
              barWidth: 40,//固定柱子宽度
              emphasis: {
                focus: 'series'
              },
              data: y1
            },
            {
              name: '采购量',
              type: 'bar',
              barWidth: 40,//固定柱子宽度
              emphasis: {
                focus: 'series'
              },
              data:y2
            },
            {
              name: '发货量',
              type: 'bar',
              barWidth: 40,//固定柱子宽度
              emphasis: {
                focus: 'series'
              },
              data: y3
            },
          ]
        });
        this.loadingChart = false;
      },

      handleSearchList(){
        this.params.pageNum = 1;
        this.getListData();
        this.getCategoryList();
      },

      handleSizeChange(val){
        this.params.pageNum = 1;
        this.params.pageSize = val;
        this.getListData();
      },

      handleCurrentChange(val){
        this.params.pageNum = val;
        this.getListData();
      },

      getListData(){
        this.loading = true;
        let fn = goodsPricePriceList;
        let data = {};
        data.pageNum = this.params.pageNum;
        data.pageSize = this.params.pageSize;
        data.addDate = this.params.date;
        if(this.params.tab == 'all'){
          fn = dayGoodsPrice;
        }else{
          data.sort = this.sort;
          data.goodsKingId = this.params.goodsKingId;
          data.categoryName = this.params.tab;
        }
        fn(data).then(response => {
          this.list = response.list;
          this.count = response.count;
          this.loading = false;
        }).catch(()=>{
          this.loading = false;
        });
      },
    },
  }
</script>

<style scoped lang="scss">
  .number-div{
    overflow: hidden;
    padding:20px;
  }
  .number-col{
    width:180px;
    border:1px solid #DCDFE6;
    float:left;
    text-align: center;
    margin-right:20px;
    margin-bottom:20px;
    padding:12px 0;
    border-radius: 10px;
    cursor: default;
  }
  .number-col .number-type{
    font-size:24px;
    font-weight: bold;
    line-height: 42px;
  }
  .number-col .number-name{
    font-size:14px;
    color:#666;
    margin-top:5px;
  }
</style>
